Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Sets

Looping set items

Iterate set in python

A set is an unordered collection of unique elements, and you can iterate over it in several ways:

1. Using a for loop

This is the most straightforward way to loop through all elements in a set.
Iterating set using for loop in python # Create a set my_set = {1, 2, 3, 4, 5} print("Original Set:", my_set) # Loop through the set for item in my_set: print(item)

Output

Original Set: {1, 2, 3, 4, 5} 1 2 3 4 5

2. Using a for loop with the enumerate() function

If you want to get both the index and the value of each element in the set, you can use the enumerate() function. However, keep in mind that sets are unordered, so the index doesn’t have a meaningful order.
Looping set using enumerate() function in python # Create a set my_set = {1, 2, 3, 4, 5} print("Original Set:", my_set) # Loop through the set with index for i, item in enumerate(my_set): print(f"Element {i} is {item}")

Output

Original Set: {1, 2, 3, 4, 5} Element 0 is 1 Element 1 is 2 Element 2 is 3 Element 3 is 4 Element 4 is 5

3. Using set comprehension

Set comprehension is a concise way to create a new set by iterating over an existing set and applying a condition.
Loop or iterate set using set comprehension python # Create a set my_set = {1, 2, 3, 4, 5} print("Original Set:", my_set) # Create a new set with only the even numbers even_set = {item for item in my_set if item % 2 == 0} print("Even Numbers Set:", even_set)

Output

Original Set: {1, 2, 3, 4, 5} Even Numbers Set: {2, 4}

Remember, because sets are unordered, you can’t make assumptions about the order in which you visit the elements of the set. The order may differ on multiple executions of the same loop.

  📌TAGS

★python ★ sets

Tutorials